package com.yzf.wisecoder.wisecoderservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yzf.accounting.common.core.utils.security.RSACoderUtil;
import com.yzf.accounting.common.core.utils.security.UrlDesEncodUtil;
import com.yzf.wisecoder.wisecodercommon.exception.RRException;
import com.yzf.wisecoder.wisecodercommon.utils.SecurityUtils;
import com.yzf.wisecoder.wisecodercommon.vo.DingUserVo;
import com.yzf.wisecoder.wisecoderservice.service.DingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author jianghuiyong
 * @Description DingTalk服务
 * @date 2020/5/8 14:32
 */
@Service("DingService")
@Slf4j
public class DingServiceImpl implements DingService {

    @Value("${dingding.agent.url}")
    private String dingAgentUrl;

    @Value("${dingding.agent.privateKey}")
    private String dingAgentPrivateKey;

    @Autowired
    private RestTemplate restTemplate;

    private static final String CODE = "code";
    private static final String DATA = "data";
    private static final String SUCCESS = "100";


    @Override
    public List<DingUserVo> getDingUsers(String name) {
//        HttpHeaders headers = generateDingAgentHeaders();
//        HttpEntity request = new HttpEntity<>(null, headers);
//        String requestUrl = dingAgentUrl + "/dingTalk/api/v1/open/getDingUser?isFired=0&pageSize=9999";
//        if (StrUtil.isNotBlank(name)) {
//            requestUrl += "&name=" + name;
//        }
//        log.info("DingService.getDingUsers() -> request url:{}", requestUrl);
//        JSONObject jsonObject = restTemplate.postForObject(requestUrl, request, JSONObject.class);
//        log.info("DingService.getDingUsers() -> response:{}", jsonObject.toJSONString());
//        JSONArray jsonArray = getDataList(jsonObject);
//        if (jsonArray == null) {
//            return Lists.newArrayList();
//        }
//        List<DingUserVo> list = jsonArray.toJavaList(DingUserVo.class);
        DingUserVo dingUserVo = new DingUserVo();
        dingUserVo.setName("卢成远");
        dingUserVo.setUuid(540764665L);
        List<DingUserVo> list = Lists.newArrayList(dingUserVo);
        return list;
    }

    @Override
    public DingUserVo getLoginUser() {
//        HttpHeaders headers = generateDingAgentHeaders();
//        HttpEntity request = new HttpEntity<>(null, headers);
//        String requestUrl = dingAgentUrl + "/dingTalk/api/v1/open/getDingUserByUnionId?unionId=" + SecurityUtils.getUnionId();
//        log.info("DingService.getLoginUser() -> request url:{}", requestUrl);
//        JSONObject responseObject = restTemplate.postForObject(requestUrl, request, JSONObject.class);
//        log.info("DingService.getLoginUser() -> response:{}", responseObject.toJSONString());
//        DingUserVo dingUserVo = parseResponse2DingUser(responseObject);
        DingUserVo dingUserVo = new DingUserVo();
        dingUserVo.setName("卢成远");
        dingUserVo.setUuid(540764665L);
        return dingUserVo;
    }

    /**
     * 生成签名的header
     *
     * @return
     */
    private HttpHeaders generateDingAgentHeaders() {
        if (StrUtil.isBlank(dingAgentPrivateKey)) {
            log.error("dingding.agent.privateKey 为空!");
            throw new RuntimeException("dingding.agent.privateKey 为空!");
        }

        if (StrUtil.isBlank(dingAgentUrl)) {
            log.error("dingding.agent.url 为空!");
            throw new RuntimeException("dingding.agent.url 为空!");
        }

        long timestamp = System.currentTimeMillis();
        String ts = String.valueOf(timestamp);

        byte[] encryptByPrivateKey = null;
        try {
            // 私钥加密
            encryptByPrivateKey = RSACoderUtil.encryptByPrivateKey(ts.getBytes(), dingAgentPrivateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Base64 加密
        String privateKeyBase64 = UrlDesEncodUtil.byte2Base64StringFun(encryptByPrivateKey);

        HttpHeaders headers = new HttpHeaders();
        headers.set("sign", privateKeyBase64);
        headers.set("timestamp", ts);
        return headers;
    }

    /**
     * jsonObject转化成DingUserDto
     *
     * @param jsonObject
     * @return
     */
    private JSONArray getDataList(JSONObject jsonObject) {
        if (SUCCESS.equals(jsonObject.getString(CODE))) {
            if (jsonObject.getJSONObject(DATA) != null) {
                return jsonObject.getJSONObject(DATA).getJSONArray("list");
            } else {
                return null;
            }
        }
        log.error("DingService.parseDingUsers() -> dingding agent invoke error！{}", jsonObject);
        throw new RRException("获取钉钉用户失败");
    }

    /**
     * jsonObject转化成DingUserDto
     *
     * @param jsonObject
     * @return
     */
    private DingUserVo parseResponse2DingUser(JSONObject jsonObject) {
        if (SUCCESS.equals(jsonObject.getString(CODE))) {
            if (jsonObject.getJSONObject(DATA) != null) {
                DingUserVo dingUserVo = jsonObject.getObject(DATA, DingUserVo.class);
                return dingUserVo;
            } else {
                return null;
            }
        }

        log.error("DingService.parseResponse2DingUser() -> dingding agent invoke error！{}", jsonObject);
        throw new RRException("获取钉钉用户信息失败");
    }

}
